package com.ulife.category.module.screen;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.Navigator;
import com.ulife.category.dao.CategoryDao;
import com.ulife.category.dao.PropertyDao;
import com.ulife.category.dao.PropertyValueDao;
import com.ulife.category.dao.dataobject.CategoryDo;
import com.ulife.category.dao.dataobject.PropertyDo;
import com.ulife.category.dao.dataobject.PropertyValueDo;
import com.ulife.category.module.vo.PropertyVo;
import com.ulife.common.ErrorMessage;

public class Propertylist {
	private static final Logger log = LoggerFactory.getLogger(Propertylist.class);

	@Autowired
	private CategoryDao categoryDao;

	@Autowired
	private PropertyDao propertyDao;

	@Autowired
	private PropertyValueDao propertyValueDao;

	@Autowired
	private HttpServletRequest request;

	public void execute(Context context, Navigator nav) {
		context.put("module", "property");
		try {
			String catId = request.getParameter("catId");
			if (StringUtils.isBlank(catId)) {
				context.put("msg", ErrorMessage.NOT_EXIST_CATEGORY);
				nav.forwardTo("message");
				return;
			}
			CategoryDo pCate = categoryDao.queryCategoryById(Long.valueOf(catId));
			if (pCate == null) {
				context.put("msg", ErrorMessage.NOT_EXIST_CATEGORY);
				nav.forwardTo("message");
				return;
			}

			List<PropertyDo> ps = propertyDao.queryPropertysByCId(pCate.getcId());

			List<PropertyVo> pForView = new ArrayList<PropertyVo>();
			for (PropertyDo propertyDo : ps) {
				PropertyVo pv = new PropertyVo();
				BeanUtils.copyProperties(propertyDo, pv);

				StringBuffer pValue = new StringBuffer();
				List<PropertyValueDo> pvdos = propertyValueDao.queryPropertyValuesByPId(propertyDo.getpId());
				for (PropertyValueDo pvDo : pvdos) {
					pValue.append(pvDo.getPvId() + ":");
					pValue.append(pvDo.getPvName() + ":");
					if (null != pvDo.getPvCode()) {
						pValue.append(pvDo.getPvCode());
					}
					pValue.append(";");
				}

				pv.setpValues(pValue.toString());
				pForView.add(pv);
			}
			context.put("propertys", pForView);
			context.put("categroy", pCate);
		} catch (Exception e) {
			log.error("propertylist error!", e);
		}
	}

}
